<template>
  <yd-layout>
    <!-- 顶部导航 -->
    <yd-navbar slot="navbar" title="确认订单" height=".88rem" bgcolor="#fff" color="#444" fontsize=".3rem">
      <yd-navbar-back-icon slot="left" color="#666" @click.native="$router.back()"></yd-navbar-back-icon>
    </yd-navbar>

    <w-empty v-if="!orderFormInfo.goodsVoList.length"></w-empty>
    <div class="m-confirm-order" v-else>
      <!-- 地址 -->
      <section class="m-confirm-order-address">
        <yd-cell-item arrow @click.native="$router.push(`/address?redirect=${encodeURIComponent($route.fullPath)}`)">
          <yd-icon slot="icon" name="location" size=".42rem"></yd-icon>
          <div slot="left">
            <div class="name-box">
              <p>{{targetAddress.trueName}}</p>
              <p>{{targetAddress.mobile}}</p>
            </div>
            <p class="detail">{{targetAddress.provinceName}}{{targetAddress.cityName}}{{targetAddress.areaName}}{{targetAddress.area_info}}</p>
          </div>
        </yd-cell-item>
      </section>
      
      <section class="order-list">订单清单</section>
      <section class="m-confirm-order-item" v-for="(goods, goodsIndex) in orderFormInfo.goodsVoList" :key="goodsIndex">
        <div class="tit">订单{{goodsIndex + 1}}</div>
        <div class="info-box">
          <div class="img-box">
            <img class="minimg" v-lazy="goods.goodsPhotoPath" />
          </div>
          <div class="text">
            <p>{{goods.goodsName}}</p>
            <em>剩余：<yd-countdown :time="goods.fightGoodsEndTime" doneText="火拼已结束"></yd-countdown></em>
          </div>
        </div>

        <div class="gsp-item" v-for="(gsp, gspIndex) in goods.goodsGsp" :key="gspIndex">
          <div class="c-box">
            <p>颜色：{{gsp.goodsSpecContent[0]}}&nbsp;&nbsp;&nbsp;尺码：{{gsp.goodsSpecContent[1]}}</p>
            <p>￥{{gsp.nowPrice | currency}}</p>
          </div>
          <div class="num-box">
            <p>{{gsp.count}}件</p>
            <em>￥{{gsp.price | currency}}</em>
          </div>
        </div>
        
        <div class="total-box">
          <div class="ship">
            <span>运费计算</span>
            <em>￥{{goods.shipPrice | currency}}</em>
          </div>
          <input type="text" v-model="goods.msg" maxlength="100" placeholder="给卖家留言">
        </div>
      </section>
    </div>

    <div slot="bottom" class="m-confirm-order-total" v-if="orderFormInfo.goodsVoList.length">
      <div class="amount">
        <p>贷款总计：￥{{parseFloat(orderFormInfo.goodsTotalPrice) | currency}}<br>运费总计：￥{{orderFormInfo.shipPrice | currency}}</p>
        <p class="text">合计：<em>￥{{(parseFloat(orderFormInfo.goodsTotalPrice)+parseFloat(orderFormInfo.shipPrice)) | currency}}</em></p>
      </div>
      <button @click="onSubmitOrder">提交订单</button>
    </div>
  </yd-layout>
</template>

<script>
  import { apiAboutUs, apiAddressAll, apiSelectAllOrder, apiShipPrice, apiAddOrder } from 'js/api'
  import { session } from 'util/storage'
  import { mapGetters } from 'vuex'

  export default {
    data() {
      return {
        aboutUsText: '',
        origin: '', // cart 购物车
        orderFormInfo: {
          goodsVoList: []
        },
        targetAddress: {},
        targetAddressId: ''
      }
    },
    created() {
      // 获取地址和处理选择地址
      apiAddressAll(this.token).then(data => {
        const aAddress = data.addressList
        if (!aAddress.length) {
          this.$toast('请先新增一条收货地址', () => {
            this.$router.replace(`/address/manage?redirect=${encodeURIComponent(this.$route.fullPath)}`)
          })
          return
        }
        const addressId = this.$route.query.addressid || ''
        if (addressId) {
          const newAddress = aAddress.filter(address => {
            return address.id == addressId
          })
          this.targetAddress = newAddress[0] || {}
        } else {
          const aNAddress = aAddress.filter(address => {
            return address.default_val == 1
          })
          this.targetAddress = aNAddress[0] || {}
        }
        this.targetAddressId = this.targetAddress.id + ''
        // 获取订单信息
        this.fetchOrderFormData()
      })
    },
    methods: {
      fetchOrderFormData() {
        // 判断来源，并且获取数据，须在地址接口获取后获取
        this.origin = this.$route.query.origin || ''
        // 来源购物车
        if (this.origin == 'cart') {
          apiSelectAllOrder(this.token).then(data => {
            this.orderFormInfo = data || {}
            // 处理成订单需要的数据
            this.orderFormInfo.orderType = 'weixin'
            this.orderFormInfo.payType = 'online'
            this.orderFormInfo.transport = '快递'
            let goodsTotalPrice = 0
            this.orderFormInfo.goodsVoList.forEach((goods, goodsIndex) => {
              goods.count = 0
              goodsTotalPrice += parseFloat(goods.goodsPrice)
              goods.msg = ''
              goods.goodsGsp.forEach(gsp => {
                goods.count += gsp.count
              })
            })
            this.$set(this.orderFormInfo, 'goodsTotalPrice', goodsTotalPrice)
            this.fetchShipPrice()
          })
        } else { // 来源立即拼单
          this.orderFormInfo = session.get('orderFormData') || {}
          this.fetchShipPrice()
        }
      },
      // 获取邮费
      fetchShipPrice() {
        const goodsList = []
        this.orderFormInfo.receiverAddrId = this.targetAddressId + ''
        this.orderFormInfo.accessToken = this.token
        this.orderFormInfo.goodsVoList.forEach(goods => {
          goodsList.push({
            id: Number(goods.goodsId || 0),
            count: Number(goods.count || 0)
          })
        })
        apiShipPrice(this.targetAddressId, goodsList).then(data => {
          const oData = data || {}
          this.$set(this.orderFormInfo, 'shipPrice', oData.shipPrice)
          const aSingleShipPrice = oData.singlePriceList || []
          aSingleShipPrice.forEach(ship => {
            this.orderFormInfo.goodsVoList.forEach(goods => {
              if (ship.goodsId == goods.goodsId) {
                goods.shipPrice = ship.singleGoodsPrice
              }
            })
          })
        })
      },
      // 提交订单
      onSubmitOrder() {
        // 最后提交是转化数据格式
        this.orderFormInfo.goodsVoList.forEach(goods => {
          goods.storeId = goods.storeId + ''
          goods.goodsId = goods.goodsId + ''
          goods.shipPrice = goods.shipPrice + ''
          goods.goodsGsp.forEach(gsp => {
            gsp.count = gsp.count + ''
          })
        })
        // 新增请求
        apiAddOrder(this.orderFormInfo).then(data => {
          const ids = (data || {}).ids
          this.$router.replace(`/cart/pay?ids=${ids.join(',')}`)
        })
      }
    },
    computed: {
      ...mapGetters(['token'])
    }
  }
</script>

<style lang="scss">
  @import '../../scss/_flex.scss';
  @import '../../scss/_mixin.scss';
  .m-confirm-order {
    min-height: 100%;
    .order-list {
      height: .54rem;
      line-height: .54rem;
      text-align: center;
      color: #666;
      border-bottom: 1px solid #eee;
      background: #fff;
    }
  }
  .m-confirm-order-address {
    padding: .3rem 0;
    margin-bottom: .2rem;
    color: #999;
    background: #fff;
    .name-box {
      @include flex();
      max-width: 5.6rem;
      overflow: hidden;
      padding-bottom: .15rem;
      color: #333;
    }
    .detail {
      @include cutoff();
      max-width: 5.6rem;
      color: #333;
    }
  }
  .m-confirm-order-item {
    margin-bottom: .2rem;
    background: #fff;
    em {
      color: #f00385;
    }
    .tit {
      height: .64rem;
      padding-left: .24rem;
      line-height: .64rem;
      color: #f00385;
    }
    .info-box {
      @include flex(start);
      background: #fafafa;
      padding: .24rem;
      .img-box {
        width: 1.54rem;
        height: 1.54rem;
        overflow: hidden;
        img {
          width: 100%;
          height: 100%;
        }
      }
      .text {
        padding-left: .24rem;
        p {
          padding-bottom: .1rem;
        }
      }
    }
    .gsp-item {
      @include flex();
      padding: .2rem .24rem;
      border-bottom: 1px solid #eee;
      .c-box {
        color: #999;
      }
      .num-box {
        text-align: right;
        color: #333;
      }
      p {
        margin-bottom: .1rem;
      }
    }
    .total-box {
      padding: .2rem .24rem .3rem;
      .ship {
        @include flex();
      }
      input {
        width: 100%;
        height: .6rem;
        padding: 0 .1rem;
        margin-top: .3rem;
        border: 1px solid #eee;
      }
    }
  }
  .m-confirm-order-total {
    position: relative;
    z-index: 20;
    border-top: 1px solid #eee;
    .amount {
      @include flex();
      height: 1.1rem;
      padding: 0 .24rem;
      background: #fff;
    }
    p {
      line-height: .36rem;
    }
    .text {
      color: #999;
      em {
        font-size: .3rem;
        color: #f00385;
      }
    }
    button {
      width: 100%;
      height: .98rem;
      background: #f00385;
      font-size: .30rem;
      color: #fff;
    }
  }
</style>